package com.nmgs.util.zip;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;

public class ZipUtil {
    private static final Logger log = LoggerFactory.getLogger(ZipUtil.class);
    public static void doUnzip(String fileName) throws Exception {
        File f = new File(fileName);
        String fileDir = f.getParent();
        log.debug("path is {}", fileDir);
        doUnzip(fileName, fileDir);
    }

    public static void doUnzip(String fileName, String dir) throws Exception {
        // 文件输入流
        try (FileInputStream fi = new FileInputStream(fileName);) {
            doUnzip(fi, dir);
        }
    }

    public static void doUnzip(File file, String dir) throws Exception {
        // 文件输入流
        try ( FileInputStream fi = new FileInputStream(file);) {
            doUnzip(fi, dir);
        }
    }

    public static void doUnzip(InputStream fi, final String dir) throws Exception {
        try ( // 输入流检查
              CheckedInputStream csi = new CheckedInputStream(fi, new Adler32()); // 输入流压缩
              ZipArchiveInputStream zipin = new ZipArchiveInputStream(csi)) {
            ZipArchiveEntry ze;
            while ((ze = zipin.getNextZipEntry()) != null) {
                String name = ze.getName();
                log.debug("name is {}", name);
                File newFile = UtilFile.newFileWithCheck(dir, name);
                if (ze.isDirectory()) {

                    if (!newFile.exists()) {
                        newFile.mkdirs();
                    }
                } else {
                    if (!newFile.getParentFile().exists()) {
                        newFile.getParentFile().mkdirs();
                    }
                    //newFile.createNewFile();
                    try (OutputStream out = new FileOutputStream(newFile);) {
                        UtilFile.copyNoClose(zipin, out);
                    }
                }
            }
        }
    }
}
